package com.ztools.wx.async;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ztools.api.service.pc.PcStudentService;
import com.ztools.common.model.pc.information.WeChatMember;
import com.ztools.common.util.common.Result;
import com.ztools.common.util.common.ResultCode;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author:seeTools
 * @Date: 2023/4/8  21:39
 * @Version 1.0
 */
@Component
public class WxMpAsyncTasks {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Reference(version = "1.0", check = false, timeout = 6000)
    private PcStudentService pcStudentService;

    @Async
    public void subscribe(WxMpUser wxMpUser) {
        WeChatMember weChatMember = WeChatMember.builder()
                .openid(wxMpUser.getOpenId())
                .name(wxMpUser.getNickname())
                .sex(wxMpUser.getSex())
                .unionId(wxMpUser.getUnionId())
                .province(wxMpUser.getProvince())
                .registrationDate(new Date())
                .city(wxMpUser.getCity())
                .build();
        if (StrUtil.isBlank(wxMpUser.getNickname())) {
            weChatMember.setNickName("新用户:" + DateUtil.formatDateTime(new Date()));
        }
        Result result = pcStudentService.subscribe(weChatMember);
        if (result.getCode() == ResultCode.SUCCESS.getCode()) {
            logger.info("调用会员注册接口成功:{}", result);
        } else {
            logger.warn("调用会员注册接口出错:{}", result);
        }
    }

    @Async
    public void updateMemberNickName(String openId, String nickName) {
        pcStudentService.updateMemberNickName(openId, nickName);
    }

}
